package com.epi.utils;

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * JWT 工具类
 */
@Component
public class JwtUtil {
    private static final String JWT_KEY = "Epiphany"; // 至少32字符
    private static final Long JWT_TTL = TimeUnit.HOURS.toMillis(1); // 1小时
    private static final SecretKey SECRET_KEY = generalKey();

    /**
     * 生成密钥
     */
    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     * 生成UUID
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 创建JWT Builder
     */
    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid, Map<String, Object> claims) {
        long nowMillis = System.currentTimeMillis();
        long expMillis = nowMillis + Optional.ofNullable(ttlMillis).orElse(JWT_TTL);

        JwtBuilder builder = Jwts.builder()
            .setId(uuid)
            .setSubject(subject)
            .setIssuer("epi")
            .setIssuedAt(new Date(nowMillis))
            .setExpiration(new Date(expMillis))
            .signWith(SignatureAlgorithm.HS256, SECRET_KEY);

        if (claims != null) {
            builder.setClaims(claims);
        }

        return builder;
    }

    /**
     * 创建JWT (简单版)
     */
    public static String createJWT(String subject) {
        return createJWT(subject, null, getUUID(), null);
    }

    /**
     * 创建JWT (完整版)
     */
    public static String createJWT(String subject, Long ttl, String uuid, Map<String, Object> claims) {
        return getJwtBuilder(subject, ttl, uuid, claims).compact();
    }

    /**
     * 解析JWT
     */
    public static Claims parseJWT(String jwt) throws ExpiredJwtException, UnsupportedJwtException,
        MalformedJwtException, SignatureException, IllegalArgumentException {
        return Jwts.parser()
            .setSigningKey(SECRET_KEY)
            .parseClaimsJws(jwt)
            .getBody();
    }

    /**
     * 验证JWT是否有效
     */
    public static boolean validateJWT(String jwt) {
        try {
            parseJWT(jwt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 刷新JWT
     */
    public static String refreshJWT(String jwt, Long newTtl) {
        Claims claims = parseJWT(jwt);
        return createJWT(
            claims.getSubject(),
            newTtl,
            claims.getId(),
            new HashMap<>(claims)
        );
    }

    /**
     * 获取JWT中的subject
     */
    public static String getSubject(String jwt) {
        return parseJWT(jwt).getSubject();
    }

    /**
     * 获取JWT中的自定义claim
     */
    public static Object getClaim(String jwt, String claimName) {
        return parseJWT(jwt).get(claimName);
    }
}